`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2022/05/15 21:52:07
// Design Name: 
// Module Name: pwm
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////

/*
module pwm(

 input sys_clk,
 input sys_rst_n,
 input [31:0]slv_reg0,
 input [31:0]slv_reg1,
 input slv_reg2,
 
 output [31:0]pwm_period,
 output [31:0]duty_cycle,
 output pwm_en
); 

assign pwm_period 	= slv_reg0;
assign duty_cycle 	= slv_reg1;
assign pwm_en 		= slv_reg2;

 always @(posedge sys_clk) begin
	if ((sys_rst_n == 1'b0) begin
		pwm_period 	<= 32'd0;
		duty_cycle 	<= 32'd0;
	end
	else begin
		
		duty_cycle <= slv_reg0[31:0];
		pwm_period <= slv_reg1[31:0];
		pwm_en <= slv_reg2;
	end
end
endmodule
*/
module pwm(
	input pwm_clk , 		//时钟信号
	input pwm_rst_n , 		//复位信号
	input pwm_en , 			//PWM输出使能信号0：禁用，1：使能
//	input [23:0]pwm_num,	//输出PWM周期个数，0代表连续输出
	input [31:0]pwm_period,	//PWM频率，=pwm_clk/pwm频率
	input [31:0]duty_cycle,	//PWM设置高电平占空比计数值
 
	output pwm //pwm
    );

//	reg [23:0] period_cnt ; //周期计数器
	reg [31:0] duty_cnt;	//PWM设置高电平占空比计数值
//	reg period_cnt_flag;
 //将周期信号计数值与占空比计数值进行比较，以输出驱动 pwm 的 PWM 信号	
	assign pwm = (( duty_cnt <= duty_cycle ) ? 1'b1 : 1'b0) & pwm_en;

 always @(posedge pwm_clk) begin
	if ((pwm_rst_n == 1'b0)||(pwm_en == 1'b0)) begin
		duty_cnt 	<= 32'd0;
		//period_cnt 	<= 24'd0;
		//period_cnt_flag <= 1'd1;
	end
	else begin
		duty_cnt <= duty_cnt + 32'd1;
		if(duty_cnt >= pwm_period) begin
			duty_cnt <= 32'd0;
		/*	if(pwm_num > 0) begin
				period_cnt <= period_cnt + 24'd1;
				if(period_cnt >= pwm_num)
					period_cnt_flag <= 1'b0;
			end*/
		end
	end
end

endmodule